import os
import main_beat_detector
import main_audio_video_synthesis
from src.Snowflake import SnowflakeIDGenerator
import shutil
import subprocess
import re

'''运行bat命令修复视频并输出到指定文件夹'''


def repair_video(input, repaired_output_dir, repair_bat_path):
    repaired_output_dir = os.getcwd() + os.sep + repaired_output_dir
    out_file = repaired_output_dir + os.sep + os.path.basename(input)
    if os.path.exists(out_file):
        print(f"{out_file} exists.")
        return
    # 删除指定文件
    delete_files_in_folder(f"{repaired_output_dir}{os.sep}cropped_faces")
    delete_files_in_folder(f"{repaired_output_dir}{os.sep}enhance_aligned")
    delete_files_in_folder(f"{repaired_output_dir}{os.sep}final_results")
    input = os.getcwd() + os.sep + input
    cmd = f"{repair_bat_path}repair_video.bat -pydir {repair_bat_path} -i {input} -o {repaired_output_dir} -w 0.5 -bu None -fps 30"
    print(f"cmd命令为{cmd}")
    os.system(cmd)

    # 使用 subprocess.run 执行命令并捕获输出
    #  encoding = 'utf-8'
    # process = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    #
    # # process.stdout 和 process.stderr 包含命令的输出和错误
    # # 确保以正确的编码解码输出
    # stdout_output = process.stdout.encode(encoding).decode(encoding, errors='ignore')
    # stderr_output = process.stderr.encode(encoding).decode(encoding, errors='ignore')
    #
    # # 打印输出
    # print("标准输出:")
    # print(stdout_output)
    #
    # print("标准错误:")
    # print(stderr_output)
    #
    # # 检查命令是否成功执行
    # if process.returncode != 0:
    #     print("命令执行失败，返回码:", process.returncode)


'''删除指定文件夹'''


def delete_files_in_folder(folder_path):
    if os.path.exists(folder_path):
        for filename in os.listdir(folder_path):
            file_path = os.path.join(folder_path, filename)
            try:
                if os.path.isfile(file_path):
                    os.remove(file_path)
            except Exception as e:
                print(f"Error while deleting {file_path}: {e}")


'''  去除文件名中的中文，才能保证codeformer正常运行'''


def copy_to_cache(input_mp4, new_file):
    if os.path.exists(new_file):
        print(f"{new_file} exists.")
        return
    folder = os.path.dirname(new_file)
    if not os.path.exists(folder):
        os.makedirs(folder)
    shutil.copy2(input_mp4, new_file)


def repaired_video(input_video, repaired_video_output_dir, music_dir, repair_video_bat_path):
    fileName = os.path.basename(input_video).split(".mp4")[0]
    output_mp3_file = f"{music_dir}{os.sep}{fileName}.mp3"
    new_file = re.sub(r'[\u4e00-\u9fff\s]+', '', fileName)
    cache_video = f"{repaired_video_output_dir}{os.sep}cache{os.sep}{new_file}.mp4"
    repaired_cache_video = f"{repaired_video_output_dir}{os.sep}{new_file}.mp4"
    out_put = f"{os.getcwd()}{os.sep}{repaired_video_output_dir}{os.sep}{fileName}.mp4"

    # 最终结果是否存在
    if os.path.exists(out_put):
        print(f"{out_put} exists.")
        return out_put
    # 拆分音频
    main_beat_detector.mp4_to_mp3(music_dir, input_video, output_mp3_file)
    # 移动到缓存目录
    copy_to_cache(input_video, cache_video)
    # 高清修复
    repair_video(cache_video, repaired_video_output_dir, repair_video_bat_path)
    # 合成音频
    main_audio_video_synthesis.add_audio_to_video(repaired_cache_video, output_mp3_file, out_put)
    # 删除高清修复的文件
    os.remove(repaired_cache_video)
    # 删除临时缓存文件
    delete_files_in_folder(f"{repaired_video_output_dir}{os.sep}cache")
    return out_put


if __name__ == "__main__":
    # 需要修复的视频
    input_video = r"output\7166038352011988992.mp4"
    # 修复视频的bat脚本位置
    repair_video_bat_path = "F:\\Software\CodeFormerGUI\\"
    # repair_video_bat_path = "D:\\software\\codeFormer-GUI\\"
    # 高清修复后的输出路径
    repaired_video_output_dir = f"outputRepaired"
    # 音频保存位置
    music_dir = 'music'

    fileName = os.path.basename(input_video).split(".mp4")[0]
    output_mp3_file = f"{music_dir}{os.sep}{fileName}.mp3"
    new_file = re.sub(r'[\u4e00-\u9fff\s]+', '', fileName)
    cache_video = f"{repaired_video_output_dir}{os.sep}cache{os.sep}{new_file}.mp4"
    repaired_cache_video = f"{repaired_video_output_dir}{os.sep}{new_file}.mp4"
    out_put = f"output\\{SnowflakeIDGenerator().generate_id()}.mp4"

    # 拆分音频
    main_beat_detector.mp4_to_mp3(music_dir, input_video, output_mp3_file)
    # 移动到缓存目录
    copy_to_cache(input_video, cache_video)
    # 高清修复
    repair_video(cache_video, repaired_video_output_dir, repair_video_bat_path)
    # 合成音频
    main_audio_video_synthesis.add_audio_to_video(repaired_cache_video, output_mp3_file, out_put)
